#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-6 下午1:35
"""
主要显示了使用app.test_client()进行测试
"""


import unittest
import tempfile
import os
from flaskr import app, init_db


class FlaskrTestCase(unittest.TestCase):
    def setUp(self):
        super(FlaskrTestCase, self).setUp()
        self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()
        app.config['TESTING'] = True
        self.app = app.test_client()
        init_db()

    def tearDown(self):
        super(FlaskrTestCase, self).tearDown()
        os.close(self.db_fd)
        os.unlink(app.config['DATABASE'])

    def login(self, username, password):
        # 实现了登陆方法
        return self.app.post('/login', data={"username": username, "password": password}, follow_redirects=True)

    def logout(self):
        # 实现了退出登陆的逻辑
        return self.app.get('/logout', follow_redirects=True)

    def test_empty_db(self):
        rv = self.app.get('/')
        assert 'No entries here so far' in rv.data

    def test_login_logout(self):
        rv = self.login("admin", "default")
        assert 'You were logged in' in rv.data
        rv = self.logout()
        assert 'You were logged out' in rv.data

        rv = self.login("admin1", 'default')
        assert 'Invalid username' in rv.data

        rv = self.login('admin', '1234')
        assert 'Invalid password' in rv.data

    def test_messages(self):
        self.login('admin', 'default')
        rv = self.app.post('/add', data={
            "title": "<Hello>",
            "text": "<strong>HTML</strong>allowed here"
        }, follow_redirects=True)
        assert 'No entries here so far' not in rv.data
        assert '&lt;Hello&gt;' in rv.data
        assert '<strong>HTML</strong>allowed here' in rv.data
